package guojin.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import guojin.io.Resource;
import guojin.pojo.Configeration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author haoge
 * @version $Id XMLConfigBuilder.java, v 0.1 2021-06-10 23:31 haoge Exp $$
 */
public class XMLConfigBuilder {
    private Configeration configeration;

    public  XMLConfigBuilder(){
        this.configeration=new Configeration();
    }

    //用Log4g解析配置文件
    public Configeration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {

        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        //获取Configeration
        Element rootElementa = document.getRootElement();
        List<Element> list = rootElementa.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        configeration.setDataSource(comboPooledDataSource);
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element element : mapperList) {
            String mapperPath = element.attributeValue("resource");
            InputStream inputStream1 = Resource.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configeration);
            xmlMapperBuilder.paresMapper(inputStream1);
        }

        return configeration;
    }
}
